/* const {
	JSDOM
} = require('jsdom');
const jsdom = new JSDOM()
const {
	window
} = jsdom;
const {
	document
} = window;
global.window = window;
global.document = document;
const $ = global.jQuery = require( 'jquery' ); */
const express = require('express')
const app = express()
const fs = require('fs')
const path = require('path') //解决路径
//公共配置
const configAll = require('./configuration.js')
/* ----------------- redis配置 ----------------- */
const redis = require('redis')
const redisClient = redis.createClient(configAll.redisConfig)
/* ----------------- socket配置 ----------------- */
const {
	createServer
} = require("http");
const routers = require('./src/Routers/index.js') //路由模块
const cors = require('cors') //解决跨域
const joi = require('joi') //路由正则限制
const {
	expressjwt: analysisJwt
} = require('express-jwt') //解密token
// 192.168.1.156
app.use(express.static(path.join(__dirname, 'public')))
// 开放服务器 dist 目录,访问时会自动寻找index.html文件
app.use(express.static(path.join(__dirname, 'dist/pc')))
//解决跨域
app.use(cors())

app.use(express.json({
	limit: '2mb'
})) //解析json

//解析字符串,挂在req.auth
app.use(express.urlencoded({
	extended: true,
	limit: '2mb'
}))

//全局中间件
app.use(async (req, res, next) => {
	res.cc = function(msg, status = -1, data = null) {
		let info = {
			status,
			msg: msg instanceof Error ? msg.message : msg,
			data: data
		}
		res.send(info)
	}
	next()
})

//注册全局解析jwt/token
app.use(analysisJwt({
	secret: configAll.secreKey,
	algorithms: ['HS256']
}).unless({ //匹配不需要token接口
	path: [/^\/common\//, /getLivesList/, /getArticleListHot/, /^\/lives\//]
}))

//注册路由
app.use(routers)
//全局注册错误中间件
app.use((err, req, res, next) => {
	if (err instanceof joi.ValidationError) return res.cc(err, -1)
	//判断token
	if (err.name === 'UnauthorizedError') return res.cc('无效的token', 401)
	res.cc(err, -1)
	next()
})
//#region

//#endregion
app.listen(81, () => {
	console.log('服务器运行')
})